import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutterhello/controller/Controller.dart';
import 'package:flutterhello/util/host_util.dart';
import 'package:flutterhello/widgets/my_toast.dart';
import 'package:get/get.dart' as MyGet;

//创建dio实例
Dio dio = new Dio(new BaseOptions(baseUrl: HostUtil.getHost()));

class HttpUtils {
  HttpUtils() {
    // 在构造函数里面添加拦截器
    dio.interceptors.add(CustomInterceptors());
  }
  //get方法 path和query参数
  Future get(path, query) async {
    Response resp;
    try {
      resp = await dio.get(path, queryParameters: query);

      if (resp.statusCode == 200) {
        String val = resp.toString();
        return jsonDecode(val);
      } else {
        String val = resp.toString();
        return jsonDecode(val);
      }
    } catch (error) {
      return error;
    }
  }

  //post方法
  Future post(path, data) async {
    Response resp;
    try {
      resp = await dio.post(path, data: data);
      if (resp.statusCode == 200) {
        String val = resp.toString();
        return jsonDecode(val);
      } else {
        String val = resp.toString();
        return jsonDecode(val);
      }
    } catch (error) {
      return error;
    }
  }

  Future put(path, data) async {
    Response resp;
    try {
      resp = await dio.put(path, data: data);
      if (resp.statusCode == 200) {
        String val = resp.toString();
        return jsonDecode(val);
      } else {
        String val = resp.toString();
        return jsonDecode(val);
      }
    } catch (error) {
      return error;
    }
  }
}

class CustomInterceptors extends InterceptorsWrapper {
  final controller = MyGet.Get.put(Controller());
//future函数，可以使用异步设置
  @override
  Future onRequest(RequestOptions options) {
    //超时设置
    options.connectTimeout = 30000;
    options.receiveTimeout = 30000;
    //设置token
    if (controller.token != "") {
      options.headers["Authorization"] = "Bearer " + controller.token;
    }
    //设置请求头
    options.headers['content-type'] = "application/json ";

    // print('------------------------请求开始------------------------');
    // print('- 请求方式：${options?.method}');
    // print('- 请求数据: ${options?.data}');
    // print('- 请求头信息：${options.headers}');
    return super.onRequest(options);
  }

  @override
  Future onResponse(Response response) {
    // print('------------------------请求结束------------------------');
    return super.onResponse(response);
  }

  @override
  Future onError(DioError err) {
    // print('------------------------请求出错------------------------');
    // print('- 错误类型：${err.type}');
    // print('- 错误信息：${err.message}');
    // print('- error: $err');
    MyTost.showTost(err.message);
    return super.onError(err);
  }
}
